package com.goods.business.service.imp;

import com.goods.business.mapper.BizInStockInfoMapper;
import com.goods.business.mapper.BizInStockMapper;
import com.goods.business.mapper.BizProductMapper;
import com.goods.business.mapper.BizSupplierMapper;
import com.goods.business.service.BizInStockService;
import com.goods.common.model.business.*;
import com.goods.common.utils.ListPageUtils;
import com.goods.common.vo.business.InStockDetailVO;
import com.goods.common.vo.business.InStockItemVO;
import com.goods.common.vo.business.InStockVO;
import com.goods.common.vo.business.SupplierVO;
import com.goods.common.vo.system.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
@Transactional
public class BizInStockServiceImpl implements BizInStockService {

    @Autowired
    private BizInStockMapper bizInStockMapper;
    @Autowired
    private BizProductMapper bizProductMapper;
    @Autowired
    private BizInStockInfoMapper bizInStockInfoMapper;
    @Autowired
    private BizSupplierMapper bizSupplierMapper;

    @Override
    public PageVO<InStockVO> findInStockList(Map<String, Object> queryMap) {

        Example example = new Example(BizInStock.class);
        Example.Criteria criteria = example.createCriteria();

        if (queryMap.containsKey("inNum") && !queryMap.get("inNum").equals(""))
            criteria.andEqualTo("inNum", queryMap.get("inNum"));//入库单
        if (queryMap.containsKey("type") && !queryMap.get("type").equals(""))
            criteria.andEqualTo("type", queryMap.get("type"));//入库类别

        if (!queryMap.get("status").equals(""))
            criteria.andEqualTo("status", queryMap.get("status"));//逻辑删除
        // TODO: 2021/9/25 解决时间问题
        if (queryMap.containsKey("startTime") && !queryMap.get("createTime").equals(""))
            criteria.andBetween("createTime", queryMap.get("startTime"), queryMap.get("endTime"));

        List<BizInStock> bizInStocks = bizInStockMapper.selectByExample(example);
        List<InStockVO> inStockVOS = new ArrayList<>();
        for (BizInStock bizInStock : bizInStocks) {
            InStockVO inStockVO = new InStockVO();
            BeanUtils.copyProperties(bizInStock, inStockVO);
            //查询相关的物资来源
            BizSupplier bizSupplier = bizSupplierMapper.selectByPrimaryKey(bizInStock.getSupplierId());
            inStockVO.setOperator(bizInStock.getOperator());
            inStockVO.setSupplierId(bizSupplier.getId());
            inStockVO.setSupplierName(bizSupplier.getName());
            inStockVO.setContact(bizSupplier.getContact());
            inStockVO.setPhone(bizSupplier.getPhone());
            inStockVO.setEmail(bizSupplier.getEmail());
            inStockVO.setSort(bizSupplier.getSort());
            inStockVO.setAddress(bizSupplier.getAddress());

            inStockVOS.add(inStockVO);
        }
        List<InStockVO> page =null;
        if (queryMap.get("pageNum") != null && queryMap.get("pageSize") != null) {
            page = ListPageUtils.page(inStockVOS, Integer.parseInt((String) queryMap.get("pageSize")), Integer.parseInt((String) queryMap.get("pageNum")));
            return new PageVO<>(bizInStocks.size(), page);
        }
        return new PageVO<InStockVO>(bizInStocks.size(), inStockVOS);
    }

    @Override
    public void saveStock(InStockVO inStockVO) {
        BizInStock bizInStock = new BizInStock();

        //检查是否有物流来源，如果没有，创建一个，回显id
        Long supplierId = inStockVO.getSupplierId();
        if (supplierId == null) {
            supplierId = this.saveSupplier(inStockVO);
        }
        bizInStock.setSupplierId(supplierId);
        //生成随机的入库单
        String inNum = UUID.randomUUID().toString().substring(0, 32);
        bizInStock.setInNum(inNum);

        //获取入库的产品详情
        List<Object> products = inStockVO.getProducts();
        for (Object product : products) {
            BizInStockInfo bizInStockInfo = new BizInStockInfo();
            Map<String,Object> map = (Map<String,Object>) product;//数据类型转换
            Integer productNumber = (Integer) map.get("productNumber");
            Object productId = map.get("productId");//查询p_num
            BizProduct bizProduct = bizProductMapper.selectByPrimaryKey(productId);
            if (bizProduct != null){
                //保存info
                bizInStockInfo.setCreateTime(new Date());
                bizInStockInfo.setModifiedTime(new Date());
                bizInStockInfo.setInNum(inNum);
                bizInStockInfo.setpNum(bizProduct.getpNum());
                bizInStockInfo.setProductNumber(productNumber);
                // TODO: 2021/9/25 可修改为批量保存info
                bizInStockInfoMapper.insert(bizInStockInfo);
            }
            //保存入库单数量
            bizInStock.setProductNumber(products.size());
        }
        //设置额外的参数
        bizInStock.setOperator(inStockVO.getOperator()); //操作者name
        bizInStock.setCreateTime(new Date()); //创建的时间
        bizInStock.setModified(new Date()); //修改的时间
        bizInStock.setRemark(inStockVO.getRemark()); //标记
        bizInStock.setType(inStockVO.getType()); // 类型
        bizInStock.setStatus(2);//审核状态

        bizInStockMapper.insert(bizInStock);
    }

    @Override
    public InStockDetailVO findInStockDetailById(Long id, Integer pageNum) {
        InStockDetailVO inStockDetailVO = new InStockDetailVO();
        BizInStock bizInStock = bizInStockMapper.selectByPrimaryKey(id); //查询出入库单
        //查询入库单的商品info
        Example example = new Example(BizInStockInfo.class);
        example.createCriteria().andEqualTo("inNum", bizInStock.getInNum());
        List<BizInStockInfo> bizInStockInfos = bizInStockInfoMapper.selectByExample(example);
        List<InStockItemVO> inStockItemVOS = new ArrayList<>();//转换类
        for (BizInStockInfo bizInStockInfo : bizInStockInfos) {
            InStockItemVO inStockItemVO = new InStockItemVO();
            //查询商品信息
            Example example1 = new Example(BizProduct.class);
            example1.createCriteria().andEqualTo("pNum", bizInStockInfo.getpNum());
            BizProduct bizProduct = bizProductMapper.selectOneByExample(example1);

            inStockItemVO.setCount(bizInStockInfo.getProductNumber());
            inStockItemVO.setPNum(bizProduct.getpNum());
            inStockItemVO.setName(bizProduct.getName());
            inStockItemVO.setImageUrl(bizProduct.getImageUrl());
            inStockItemVO.setModel(bizProduct.getModel());
            inStockItemVO.setUnit(bizProduct.getUnit());
            inStockItemVOS.add(inStockItemVO);
        }
        //itemvos
        ListPageUtils.page(inStockItemVOS, 10, pageNum);
        inStockDetailVO.setItemVOS(inStockItemVOS);
        //total
        inStockDetailVO.setTotal(bizInStockInfos.size());
        //suppliervo
        BizSupplier bizSupplier = bizSupplierMapper.selectByPrimaryKey(bizInStock.getSupplierId());
        SupplierVO supplierVO = new SupplierVO();
        BeanUtils.copyProperties(bizSupplier, supplierVO);
        inStockDetailVO.setSupplierVO(supplierVO);
        //status
        inStockDetailVO.setStatus(bizInStock.getStatus());
        //type
        inStockDetailVO.setType(bizInStock.getType());
        //operator
        inStockDetailVO.setOperator(bizInStock.getOperator());
        //inNum
        inStockDetailVO.setInNum(bizInStock.getInNum());

        return inStockDetailVO;
    }

    @Override
    public void updateStatus(Integer id, Integer status) {
        BizInStock bizInStock = bizInStockMapper.selectByPrimaryKey(id);
        if (bizInStock != null){
            bizInStock.setStatus(status);
            bizInStockMapper.updateByPrimaryKey(bizInStock);
        }
    }

    @Override
    public void deleteById(Integer id) {
        //先查寻出详情
        BizInStock bizInStock = bizInStockMapper.selectByPrimaryKey(id);
        //获取outNum,删除info的信息
        Example example = new Example(BizInStockInfo.class);
        example.createCriteria().andEqualTo("inNum",bizInStock.getInNum());
        bizInStockInfoMapper.deleteByExample(example);
        bizInStockMapper.deleteByPrimaryKey(id);
    }

    private Long saveSupplier(InStockVO inStockVO) {
        BizSupplier bizSupplier = new BizSupplier();
        bizSupplier.setCreateTime(new Date());
        bizSupplier.setName(inStockVO.getSupplierName());
        bizSupplier.setAddress(inStockVO.getAddress());
        bizSupplier.setEmail(inStockVO.getEmail());
        bizSupplier.setPhone(inStockVO.getPhone());
        bizSupplier.setSort(inStockVO.getSort());
        bizSupplier.setContact(inStockVO.getContact());
        bizSupplierMapper.insert(bizSupplier);
        return bizSupplier.getId();
    }
}
